import { fetchStatus } from '@/api/global'
import { fetchGetMachineRooms } from '@/api/template'
import { IPersonalTemplate } from '@/api/template/interface'
import Alert from '@/components/Alert'
import AuthenticationCheck from '@/components/AuthenticationCheck'
import useCheckAuthentication from '@/components/AuthenticationCheck/useCheckAuthentication'
import useCreateConfs from '@/hooks/useCreateConfs'
import { useGlobalStore } from '@/store/global'
import { CheckBox, InnerInputRef, Input, Modal, Select } from '@kedacom/react-next'
import React, { useEffect, useRef, useState } from 'react'
import { StyledMeetingConveneModal } from './style'
import { fetchCheckMeetingName } from '@/api/manager/meetingInfoSet'
import { t } from 'i18next'
import { getUTF8ByteCount, regexEnum } from '@/utils'

export interface MeetingConveneModalProps {
	data: IPersonalTemplate | null
	open: boolean
	setOpen: (val: boolean) => void
}
/*
组件使用
<MeetingConveneModal data={templateData} open={isShowModal} setOpen={setIsShowModal} />
*/
export default function MeetingConveneModal(props: MeetingConveneModalProps) {
	const serverInfo = useGlobalStore((state) => state.serverInfo)
	const SWITCH = useGlobalStore((state) => state.SWITCH)
	const { data, open, setOpen } = props
	const [name, setName] = useState(data?.name ?? '')
	const [isManual, setIsManual] = useState(data?.permanent_meeting === 1)
	const [hourValue, setHourValue] = useState(getHourAndMinute(data?.duration).hour)
	const [minuteValue, setMinuteValue] = useState(getHourAndMinute(data?.duration).minute)
	const [machineRooms, setMachineRooms] = useState<{ value: string; label: string }[]>([])
	const [machineValue, setMachineValue] = useState('')
	const hourOptions = new Array(25).fill('').map((_, index) => ({ label: String(index), value: index }))
	const inputRef = useRef<InnerInputRef>(null)
	const minuteOptions =
		hourValue === 24
			? [{ label: '0', value: 0 }]
			: [
					{ label: '0', value: 0 },
					{ label: '15', value: 15 },
					{ label: '30', value: 30 },
					{ label: '45', value: 45 },
			  ]

	const { run } = useCreateConfs()

	const {
		run: checkAuthentication,
		open: isAuthenticationOpen,
		setOpen: setIsAuthenticationOpen,
		successFn,
	} = useCheckAuthentication()

	function getHourAndMinute(value?: number) {
		if (!value || data?.permanent_meeting) return { hour: 4, minute: 0 }
		let hour = Math.floor(value / 60)
		let minute = value % 60
		return { hour, minute }
	}

	useEffect(() => {
		if (open) {
			resetData()
			fetchGetMachineRooms().then((data) => {
				if (data && data.length !== 0) {
					let newData = data.map((item) => ({ value: item.moid, label: item.name }))
					setMachineRooms(newData)
					setMachineValue(newData[0].value)
				} else {
					setMachineRooms([])
				}
			})
		} else {
			setName('')
			setIsManual(false)
			setHourValue(4)
			setMinuteValue(0)
		}
	}, [open])

	useEffect(() => {
		resetData()
	}, [data])

	const resetData = () => {
		setName(data?.name ?? '')
		setIsManual(data?.duration === 0)
		setHourValue(getHourAndMinute(data?.duration).hour)
		setMinuteValue(getHourAndMinute(data?.duration).minute)
	}

	const handleOK = async () => {
		if (!data) return
		let duration = hourValue * 60 + minuteValue
		if (duration <= 0 && !isManual) {
			Alert(t('会议时长不能为0'))
			return
		}
		let flag = await inputRef.current?.valid()
		if (!flag) {
			Alert(t('请输入正确的会议名称'))
			return
		}
		if (!machineValue) {
			Alert(t('请选择机房'))
			return
		}
		setOpen(false)
		fetchStatus(() => {
			run(
				{
					create_type: 3,
					template_id: data.template_id,
					duration: isManual ? 0 : hourValue * 60 + minuteValue,
					name: name,
					specified_machine_room_moid: machineValue,
				},
				checkAuthentication
			)
		})
	}

	return (
		<>
			<Modal
				className="meeting-convene-modal"
				open={open}
				title={t('立即召开')}
				width={430}
				height={300}
				okText={t('立即召开')}
				onOk={handleOK}
				onCancel={() => {
					setOpen(false)
				}}
				cancelText={t('取消')}
			>
				<StyledMeetingConveneModal className="meeting-convene-modal__i18n">
					<div className="line">
						<div className="label">{t('会议名称')}</div>
						<Input
							innerRef={inputRef}
							width={200}
							maxLength={SWITCH.characterLimit ? 32 : undefined}
							focusMsg={SWITCH.characterLimit ? t('最多32个字符，符号仅限_ - @ . ( ) #') : undefined}
							rule={{
								required: {
									msg: t('会议名称不能为空'),
								},
								regular: SWITCH.characterLimit
									? [
											{
												regex: regexEnum.nameIllegal,
												msg: t('会议名称存在非法字符，请重新输入'),
											},
											{
												regex: (v) =>
													!/^[\u4e00-\u9fa5A-Za-z0-9]/.test(v) ||
													!/[\u4e00-\u9fa5A-Za-z0-9]$/.test(v),
												msg: t('首尾字符仅允许输入：英文、数字、汉字'),
											},
											{
												regex: async () => {
													const bol = await fetchCheckMeetingName({ conf_name: name })
													return !bol
												},
												msg: t('会议名称已存在'),
											},
									  ]
									: [
											{
												regex: (v: string) => {
													let len = getUTF8ByteCount(v)
													return len > 100
												},
												msg: t('输入内容超过长度限制'),
											},
											{
												regex: async () => {
													const bol = await fetchCheckMeetingName({ conf_name: name })
													return !bol
												},
												msg: t('会议名称已存在'),
											},
									  ],
							}}
							value={name}
							onChange={(e, val) => setName(val)}
						/>
					</div>
					<div className="line">
						<div className="label">{t('会议时长')}</div>
						<Select
							width={64}
							options={hourOptions}
							value={hourValue}
							panelMaxItemCount={4}
							panelPreventOverflow={false}
							disabled={isManual}
							onChange={(e, val) => {
								setHourValue(val)
								if (val === 24) {
									setMinuteValue(0)
								}
							}}
						/>
						<span className="unit">{t('小时')}</span>
						<Select
							width={64}
							options={minuteOptions}
							value={minuteValue}
							disabled={isManual}
							panelPreventOverflow={false}
							onChange={(e, val) => {
								setMinuteValue(val)
							}}
						/>
						<span className="unit">{t('分钟')}</span>
					</div>
					<div className="line manual">
						<CheckBox checked={isManual} onChange={(e, val) => setIsManual(val)}>
							{t('手动结束')}
						</CheckBox>
					</div>
					{!serverInfo?.stand_alone && data?.smart_cascade_mode !== 1 && !!SWITCH.template.machineValue && (
						<div className="line">
							<div className="label">{t('机房选择')}</div>
							<Select
								width={200}
								options={machineRooms}
								value={machineValue}
								panelPreventOverflow={false}
								onChange={(e, val) => {
									setMachineValue(val)
								}}
							/>
						</div>
					)}
				</StyledMeetingConveneModal>
			</Modal>
			<AuthenticationCheck open={isAuthenticationOpen} setOpen={setIsAuthenticationOpen} callBack={successFn} />
		</>
	)
}
